package com.wg.dome;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.wg.common.annotation.Init;
import com.wg.common.annotation.Service;
import com.wg.dome.annotation.Request;

import java.util.HashMap;
import java.util.Set;

/**
 * 协议管理
 *
 * @author 少爷123
 * @date 2021/4/16
 */
@Service
public class HandleRequestMgr {
    private static final Log log = LogFactory.get();
    private final HashMap<Integer, Class<?>> hashMap = new HashMap<>(100);

    @Init
    public void init() {
        Set<Class<?>> classesSet = ClassUtil.scanPackageByAnnotation(getClass().getPackage().getName(), Request.class);
        for (Class<?> classes : classesSet) {
            Request request = classes.getAnnotation(Request.class);

            if (hashMap.get(request.OperationCode()) != null){
                log.error("OperationCode duplicate. code={} class={}", request.OperationCode(), classes.getName());
                continue;
            }
            hashMap.put(request.OperationCode(), classes);
        }
    }

    @SuppressWarnings("unchecked")
    public <T> T getRequest(int operationCode) {
        try {
            Class<?> aClass = hashMap.get(operationCode);
            Object object = ReflectUtil.newInstance(aClass);
            return (T) object;
        } catch (Exception e){
            log.error("error", e);
            return null;
        }
    }
}
